//
//  MusicThiViewController.m
//  A_program
//
//  Created by 杨利佳 on 15/5/23.
//  Copyright (c) 2015年 BayMax. All rights reserved.
//

#import "MusicThiViewController.h"
#import "IntroViewController.h"
#import "ConnectModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MusicHeader.h"
#import "MusicThiModel.h"
#import "MusicThiTableViewCell.h"
#import "PlayerViewController.h"
#import "MusicModel.h"
#import "NovelModel.h"
#import "NovelDatabase.h"
#import "MusicThiButton.h"
#import "LoginNextViewController.h"
#import "NovelModel.h"

@interface MusicThiViewController ()<UITableViewDataSource, UITableViewDelegate,MusicThiButtonDelegate>

@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) MusicHeader *headView;
@property (nonatomic, retain) NovelModel *novelModel;

@end

@implementation MusicThiViewController

- (void)dealloc
{
    [_model release];
    [_ID release];
    [_tableArray release];
    [_table release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.tableArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTable];
    [self createHeader];
    [self connect];
    
    // Do any additional setup after loading the view.
}

#pragma mark -
#pragma mark 创建整个界面的tableView
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStyleGrouped];
    _table.dataSource = self;
    _table.delegate = self;
    _table.rowHeight = 170;
    [_table registerClass:[MusicThiTableViewCell class] forCellReuseIdentifier:@"cc"];
    
    [self.view addSubview:_table];
    [_table release];
    
}

// 创建tableView的header
- (void)createHeader
{
    self.headView = [[MusicHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 210)];
    _headView.backgroundColor = [UIColor lightGrayColor];
    self.table.tableHeaderView = _headView;
    [_headView release];
    self.headView.musicThiButtonActionDelegate = self;
    
    // 点击进入简介界面(按钮)
    UIButton *next = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 30, 120, 30, 30)];
    UIImage *cImage = [UIImage imageNamed:@"next.png"];
    UIImage *dImage = [cImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [next setImage:dImage forState:UIControlStateNormal];
    [next addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:next];
    [next release];
    
}

//收藏按钮的实现
#pragma mark -
#pragma mark 收藏按钮的点击实现
- (void)createCollectAction:(NSString *)collect{
    
    NSUserDefaults *myLoginName = [[NSUserDefaults alloc]init];

                NSString *collectStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15",collect];
                [ConnectModel connectWithUrl:collectStr block:^(NSData *data) {
                    self.novelModel = [[NovelModel alloc]init];
                    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableDictionary *myHeaderDic = [dic objectForKey:@"album"];
                    [self.novelModel setValuesForKeysWithDictionary:myHeaderDic];
                    //读取userDefault的信息
                    self.novelModel.loginName = [myLoginName objectForKey:@"loginName"];
                    self.novelModel.playKind = @"novel";
                    self.novelModel.albumIdMin = [collect integerValue];
                    [NovelDatabase insertWithModel:self.novelModel];
                }];


    
}



#pragma mark -
#pragma mark 点击事件


// 进入简介的界面按钮
- (void)nextAction:(id)sender
{
    IntroViewController *intro = [[IntroViewController alloc] init];
    intro.model = self.model;
    [self presentViewController:intro animated:YES completion:nil];
    
}






#pragma mark -
#pragma mark 网络请求
- (void)connect
{
    // 网络请求
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/15", self.ID];
    [ConnectModel connectWithUrl:url block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *smallDic = [dic objectForKey:@"album"];
        
        // 字典转成model传到简介界面
        self.model = [[MusicThiModel alloc] init];
        [self.model setValuesForKeysWithDictionary:smallDic];
        
        // 上面的header
        [_headView.background sd_setImageWithURL:[NSURL URLWithString:_model.coverOrigin] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        _headView.title.text = _model.title;
        [_headView.image1 sd_setImageWithURL:[NSURL URLWithString:_model.coverSmall] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        _headView.detail.text = _model.introRich;
        [_headView.showImage sd_setImageWithURL:[NSURL URLWithString:_model.coverLarge] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
        _headView.name.text = _model.nickname;
        
        // 下面的tableView
        NSDictionary *arrayDic = [dic objectForKey:@"tracks"];
        self.tableArray = [arrayDic objectForKey:@"list"];
        [_table reloadData];
        
    }];
}






#pragma mark -
#pragma mark tableView的协议实现

// 行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicThiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cc"];
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    //判断收藏按钮状态
    
    self.headView.coll.albumId = self.model.albumId;
    NSUserDefaults *myLoginName = [NSUserDefaults standardUserDefaults];
    NSInteger myAlbumId = self.headView.coll.albumId;
    NSMutableArray *array = (NSMutableArray *)[NovelDatabase selectNameAlbumId:myAlbumId loginName:[myLoginName objectForKey:@"loginName"]];
    if (array.count == 0) {
        [self.headView.coll setTitle:@"收藏" forState:UIControlStateNormal];
        
    }else{
        [self.headView.coll setTitle:@"已收藏" forState:UIControlStateNormal];
        
    }    
    //赋值部分
    [cell.showImage sd_setImageWithURL:[dic objectForKey:@"coverSmall"] placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    cell.title.text = [dic objectForKey:@"title"];
    cell.nickname.text = [NSString stringWithFormat:@"by %@", [dic objectForKey:@"nickname"]];
    
    NSInteger play = [[dic objectForKey:@"playtimes"] integerValue];
    cell.playtimes.text = [NSString stringWithFormat:@"%.1f万", play / 10000.0];
    
    cell.likes.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"likes"]];
    cell.comments.text = [NSString stringWithFormat:@"%@", [dic objectForKey:@"comments"]];
    
    NSInteger minute = [[dic objectForKey:@"duration"] integerValue] / 60;
    NSInteger second = [[dic objectForKey:@"duration"] integerValue] % 60;
    cell.duration.text = [NSString stringWithFormat:@"%ld : %ld", minute, second];
    
    
    return  cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"声音";
}

// tableView 跳转到播放界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayerViewController *play = [[PlayerViewController alloc]init];
   NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    play.trackId = [dic objectForKey:@"trackId"];
    play.array = _tableArray;
    [self presentViewController:play animated:YES completion:nil];
    [play release];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
